package com.coolmusic;

import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MusicFragment extends Fragment {
    private static final String TAG = "MusicFragment";
    private static final int PROGRESS_UPDATE_INTERVAL = 100; // 进度条更新间隔(毫秒)
    private MediaPlayer mediaPlayer;
    private final Handler handler = new Handler();
    private SeekBar songProgressBar, volumeControl;
    private TextView songTitle, songArtist, currentTime, totalTime;
    private ImageView btnPlayPause, btnPrevious, btnNext, btnShuffle, btnRepeat;
    private ImageView albumCover, btnMore; // 添加更多按钮变量
    private List<Music> musicList = new ArrayList<>();
    private int currentMusicIndex = 0;
    private boolean isShuffle = false;
    private boolean isRepeat = false;
    private View rootView;
    private AnimatorSet rotateAnimator; // 专辑封面旋转动画

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_music, container, false);
        initViews();
        initMusicList();
        initMediaPlayer();
        initRotateAnimator(); // 初始化旋转动画
        handleReceivedSongIndex();
        return rootView;
    }

    private void initViews() {
        songTitle = rootView.findViewById(R.id.song_title);
        songArtist = rootView.findViewById(R.id.song_artist);
        currentTime = rootView.findViewById(R.id.current_time);
        totalTime = rootView.findViewById(R.id.total_time);
        songProgressBar = rootView.findViewById(R.id.song_progress);
        volumeControl = rootView.findViewById(R.id.volume_control);
        btnPlayPause = rootView.findViewById(R.id.btn_play_pause);
        btnPrevious = rootView.findViewById(R.id.btn_previous);
        btnNext = rootView.findViewById(R.id.btn_next);
        btnShuffle = rootView.findViewById(R.id.btn_shuffle);
        btnRepeat = rootView.findViewById(R.id.btn_repeat);
        albumCover = rootView.findViewById(R.id.album_cover);
        btnMore = rootView.findViewById(R.id.btn_more); // 获取更多按钮

        // 设置默认图标
        btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
        btnShuffle.setImageResource(android.R.drawable.ic_menu_share);
        btnRepeat.setImageResource(android.R.drawable.ic_menu_rotate);

        setButtonListeners();
        setSeekBarListeners();
        setMoreButtonListener(); // 添加更多按钮监听
    }

    // 添加更多按钮点击事件
    private void setMoreButtonListener() {
        btnMore.setOnClickListener(v -> showMoreMenu(v));
    }

    // 显示更多菜单
    private void showMoreMenu(View view) {
        PopupMenu popupMenu = new PopupMenu(requireContext(), view);
        popupMenu.getMenuInflater().inflate(R.menu.music_menu, popupMenu.getMenu()); // 加载菜单资源

        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_scan:
                        // 跳转到扫一扫界面（需创建ScanActivity）
                        startActivity(new Intent(requireContext(), ScanActivity.class));
                        return true;
                    case R.id.action_settings:
                        // 跳转到设置界面（需创建SettingsActivity）
                        startActivity(new Intent(requireContext(), SettingsActivity.class));
                        return true;
                    default:
                        return false;
                }
            }
        });

        popupMenu.show();
    }

    // 以下为原有代码（保持不变）
    private void initMusicList() {
        // 添加示例歌曲（需替换为实际资源）
        musicList.add(new Music("我们的明天", "鹿晗", R.raw.song1, R.drawable.wmdmt));
        musicList.add(new Music("致爱", "鹿晗", R.raw.song2, R.drawable.zhiai));
        musicList.add(new Music("勋章", "鹿晗", R.raw.song3, R.drawable.xunzhang));
        // 新增歌曲
        musicList.add(new Music("晴天", "周杰伦", R.raw.song4, R.drawable.qingtian));
        musicList.add(new Music("天天", "陶喆", R.raw.song5, R.drawable.tiantian));
        musicList.add(new Music("后来", "刘若英", R.raw.song6, R.drawable.houlai));
        musicList.add(new Music("知足", "五月天", R.raw.song7, R.drawable.zhizu));

        if (!musicList.isEmpty()) {
            updateSongInfo();
        } else {
            Toast.makeText(getActivity(), "没有可用的音乐", Toast.LENGTH_SHORT).show();
        }
    }

    private void initMediaPlayer() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(mp -> handleSongCompletion());
            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                Log.e(TAG, "MediaPlayer错误: what=" + what + ", extra=" + extra);
                Toast.makeText(getActivity(), "播放错误", Toast.LENGTH_SHORT).show();
                mp.reset();
                btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
                return true;
            });
            volumeControl.setMax(100);
            volumeControl.setProgress(70);
            updateVolume(70);
        }
    }

    @SuppressLint("ResourceType")
    private void initRotateAnimator() {
        rotateAnimator = (AnimatorSet) AnimatorInflater.loadAnimator(
                requireContext(), R.anim.rotate_anim);
        rotateAnimator.setTarget(albumCover);
    }

    private void handleReceivedSongIndex() {
        if (getArguments() != null) {
            int index = getArguments().getInt("song_index", 0);
            if (index >= 0 && index < musicList.size()) {
                currentMusicIndex = index;
                playCurrentSong();
            }
        }
    }

    private void setButtonListeners() {
        btnPlayPause.setOnClickListener(v -> togglePlayPause());
        btnPrevious.setOnClickListener(v -> previousSong());
        btnNext.setOnClickListener(v -> nextSong());
        btnShuffle.setOnClickListener(v -> toggleShuffle());
        btnRepeat.setOnClickListener(v -> toggleRepeat());
    }

    private void togglePlayPause() {
        if (musicList.isEmpty()) {
            Toast.makeText(getActivity(), "无音乐可播放", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mediaPlayer.isPlaying()) {
            pauseSong();
        } else {
            playCurrentSong();
        }
    }

    private void previousSong() {
        currentMusicIndex = (currentMusicIndex - 1 + musicList.size()) % musicList.size();
        playSong(currentMusicIndex);
    }

    private void nextSong() {
        if (isShuffle) {
            currentMusicIndex = new Random().nextInt(musicList.size());
        } else {
            currentMusicIndex = (currentMusicIndex + 1) % musicList.size();
        }
        playSong(currentMusicIndex);
    }

    private void toggleShuffle() {
        isShuffle = !isShuffle;
        updateButtonColor(btnShuffle, isShuffle);
        Toast.makeText(getActivity(),
                isShuffle ? "随机播放已开启" : "随机播放已关闭",
                Toast.LENGTH_SHORT).show();
    }

    private void toggleRepeat() {
        isRepeat = !isRepeat;
        updateButtonColor(btnRepeat, isRepeat);
        Toast.makeText(getActivity(),
                isRepeat ? "单曲循环已开启" : "单曲循环已关闭",
                Toast.LENGTH_SHORT).show();
    }

    private void setSeekBarListeners() {
        songProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeCallbacks(updateProgressRunnable);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                handler.post(updateProgressRunnable);
            }
        });

        volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    updateVolume(progress);
                }
            }
            // 空实现
            @Override public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }


    private void playSong(int index) {
        if (index < 0 || index >= musicList.size()) return;

        Music music = musicList.get(index);
        try (AssetFileDescriptor afd = getResources().openRawResourceFd(music.getAudioResourceId())) {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(mp -> {
                mp.start();
                updateUIAfterPlay();
                handler.post(updateProgressRunnable); // 启动进度条更新
            });
        } catch (IOException e) {
            Log.e(TAG, "播放错误: " + e.getMessage());
            Toast.makeText(getActivity(), "无法播放歌曲", Toast.LENGTH_SHORT).show();
        }
    }

    private void playCurrentSong() {
        playSong(currentMusicIndex);
        Log.d(TAG, "播放歌曲: " + musicList.get(currentMusicIndex).getTitle());
    }

    private void pauseSong() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
            stopRotateAnimation(); // 暂停时停止动画
        }
    }

    private void updateUIAfterPlay() {
        updateSongInfo();
        btnPlayPause.setImageResource(android.R.drawable.ic_media_pause);
        songProgressBar.setMax(mediaPlayer.getDuration());
        updateAlbumCover();
        startRotateAnimation(); // 播放时启动动画
    }

    private void updateSongInfo() {
        if (currentMusicIndex < 0 || currentMusicIndex >= musicList.size()) return;
        Music music = musicList.get(currentMusicIndex);
        songTitle.setText(music.getTitle());
        songArtist.setText(music.getArtist());
    }

    private void updateAlbumCover() {
        if (albumCover == null || musicList.isEmpty()) return;
        Music currentMusic = musicList.get(currentMusicIndex);
        albumCover.setImageResource(currentMusic.getCoverResourceId());
    }

    private void updateVolume(int volumePercent) {
        if (mediaPlayer != null) {
            float volume = volumePercent / 100f;
            mediaPlayer.setVolume(volume, volume);
        }
    }

    private final Runnable updateProgressRunnable = new Runnable() {
        @Override
        public void run() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                currentTime.setText(formatTime(mediaPlayer.getCurrentPosition()));
                totalTime.setText(formatTime(mediaPlayer.getDuration()));
                songProgressBar.setProgress(mediaPlayer.getCurrentPosition());
                handler.postDelayed(this, PROGRESS_UPDATE_INTERVAL);
            }
        }
    };

    private String formatTime(int timeInMillis) {
        int seconds = timeInMillis / 1000;
        int minutes = seconds / 60;
        return String.format("%d:%02d", minutes, seconds % 60);
    }

    private void handleSongCompletion() {
        if (isRepeat) {
            playCurrentSong();
        } else if (isShuffle) {
            nextSong();
        } else {
            currentMusicIndex = (currentMusicIndex + 1) % musicList.size();
            playSong(currentMusicIndex);
        }
    }

    private void updateButtonColor(ImageView button, boolean isEnabled) {
        int color = isEnabled ? getResources().getColor(R.color.colorAccent) : getResources().getColor(android.R.color.white);
        button.setColorFilter(color);
    }

    // 动画控制方法
    private void startRotateAnimation() {
        if (!rotateAnimator.isRunning()) {
            rotateAnimator.start();
        }
    }

    private void stopRotateAnimation() {
        if (rotateAnimator.isRunning()) {
            rotateAnimator.pause(); // 暂停动画以便恢复
        }
    }

    // 生命周期处理
    @Override
    public void onResume() {
        super.onResume();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            handler.post(updateProgressRunnable);
            startRotateAnimation(); // 恢复播放时继续动画
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        handler.removeCallbacks(updateProgressRunnable);
        stopRotateAnimation(); // 暂停时停止动画
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (rotateAnimator != null) {
            rotateAnimator.cancel(); // 销毁时取消动画
            rotateAnimator = null;
        }
    }

    // 音乐数据类
    private static class Music {
        private final String title;
        private final String artist;
        private final int audioResourceId;
        private final int coverResourceId;

        public Music(String title, String artist, int audioResId, int coverResId) {
            this.title = title;
            this.artist = artist;
            this.audioResourceId = audioResId;
            this.coverResourceId = coverResId;
        }

        public String getTitle() { return title; }
        public String getArtist() { return artist; }
        public int getAudioResourceId() { return audioResourceId; }
        public int getCoverResourceId() { return coverResourceId; }
    }
}